<template>
  <div>
    <el-dialog
        v-model="visible"
        title="观察日志"
        width="40%"
        top="5vh"
        :close-on-click-modal="false"
        :before-close="handleClose"
        class="note-operate-dialog"
    >
      <div>
        <el-form-item :label="$t('loc.student')" required>
          <div class="child-list">
            <div class="child-item">
              <img :src="child.avatarUrl" style="border-radius: 50%;width: 60px; height: 60px;">
              <div class="child-name">
                {{ child.displayName }}
              </div>
            </div>
          </div>
        </el-form-item>
        <div>
          <el-form-item :label="$t('loc.description')" required>
            <el-input
                style="margin-left: 13px;"
                v-model="payload"
                type="textarea"
                :autosize="{ minRows: 6, maxRows: 10 }"
                placeholder="Please input"
            />
          </el-form-item>
        </div>
        <el-form-item :label="$t('loc.measure')" required>
          <div>
            <el-button class="select-measures-btn" @click="selectMeasuresClickHandler">{{ $t('loc.addMse') }}</el-button>
            <div>
              <el-tag style="margin: 5px 5px;" v-for="measure in selectMeasures" type="success">{{ measure.abbreviation }}</el-tag>
            </div>
          </div>
        </el-form-item>
        <el-form-item :label="$t('loc.date')" required>
          <el-date-picker style="margin-left: 12px;"
              v-model="applyDate"
              type="datetime"
              :size="size" :clearable="false"
          />
        </el-form-item>
      </div>
      <template #footer>
       <span class="dialog-footer">
              <el-button @click="handleClose">{{ $t('loc.cancel') }}</el-button>
              <el-button :loading="submitLoading" type="primary" @click="submitHandler">
                 {{ $t('loc.submit') }}
              </el-button>
          </span>
      </template>
    </el-dialog>
    <FrameworkMeasureSelect
            :frameworks="frameworks"
            @selectedMeasureIds="selectedMeasureIdsHandler"
            :select-measure-ids="selectMeasureIds"
            v-model:dialogVisible="frameworkDialogVisible"
        />

  </div>
</template>

<script>
import NoteApi from "@/api/note";
import moment from "moment";
import FrameworkApi from "@/api/framework";
import FrameworkMeasureSelect from "@/views/modules/note/component/FrameworkMeasureSelect";
export default {
  name: "NoteOperateDialog",
  components: {
    FrameworkMeasureSelect
  },
  props: {
    dialogVisible: Boolean,
    child: Object,
    note: {
      type: Object,
      default: () => {
        return {
          payload: '',
          measuresIds: [],
          applyDate: '',
        }
      }
    },
  },
  data() {
    return {
      visible: false,
      needReLoad: false,
      payload: '',
      selectMeasureIds: [],
      applyDate: moment().format('YYYY-MM-DD HH:mm:ss'),
      frameworkDialogVisible: false,
      submitLoading: false,
      frameworks: [], // 当前孩子框架
      measures: [], // 当前孩子框架的测评点
    }
  },
  watch: {
    dialogVisible: {
      immediate: true,
      handler(newVal) {
        this.visible = newVal
        if (newVal) {
          this.initData()
        }
      },
    },
  },
  computed: {
    selectMeasures() {
      // 从框架中获取选择的测评点
      if (!this.measures || this.measures.length === 0) {
        return []
      }
      return this.measures.filter(item => {
        return this.selectMeasureIds.includes(item.id)
      })
    },
  },
  methods: {
    initData() {
      this.payload = this.note.payload || ''
      this.selectMeasureIds = this.note.measures && this.note.measures.map(item=>item.id) || []

      this.noteapplyDate = this.note.payload || ''
      if (!this.frameworks || !this.frameworks[0] || this.frameworks[0].id !== this.child.frameworkId) {
          this.loadFramework()
      }
    },
    loadFramework () {
      if (!this.child.frameworkId) {
        return
      }
      FrameworkApi.getFrameworkMeasures(this.child.frameworkId).then(res => {
        this.frameworks = res.frameworks
        let framework = this.frameworks[0] || {}
        this.measures = framework.childDomains.flatMap(item => item.childDomains) || []
      })
    },
    selectMeasuresClickHandler() {
      this.frameworkDialogVisible = true
    },
    handleClose() {
      this.visible = false
      this.$emit('update:dialogVisible', this.visible)
      if (this.needReLoad === true) {
        this.needReLoad = false
        this.$emit('needReLoadData')
      }
    },
    noteCheck (note) {
      if (!note.payload) {
        this.$message({
          message: "请先描述一下你观察到的情况",
          type: 'warning'
        })
        return false
      }
      if (!note.measuresIds || note.measuresIds.length === 0) {
        this.$message({
          message: "请至少选择一个测评点",
          type: 'warning'
        })
        return false
      }
      if (!note.applyDate) {
        this.$message({
          message: this.$t('loc.dateReq'),
          type: 'warning'
        })
        return false
      }
      // 如果日期大于当前日期，提示错误
      if (moment(note.applyDate).isAfter(moment())) {
        this.$message({
          message: '不能选择未来的日期',
          type: 'warning'
        })
        return false
      }
      // 如果没有修改
      // if (this.note && this.note.payload === note.payload && this.note.measures.map() === note.measuresIds && this.note.applyDate === note.applyDate) {
      //   this.$message({
      //     message: '没有修改',
      //     type: 'warning'
      //   })
      //   return false
      // }
      return true
    },
    submitHandler() {

      const note = {
        payload: this.payload,
        measuresIds: this.selectMeasureIds,
        childIds: [this.child.id],
        type: 'Normal',
        applyDate: moment(this.applyDate).format('YYYY-MM-DD HH:mm:ss'),
      }
      if (!this.noteCheck(note)) {
        return
      }
      if (this.note.id) {
        note.id = this.note.id
         this.updateNoteHandler(note)
      } else {
        this.submitLoading = true
        NoteApi.createNote(note).then(res => {
          this.submitLoading = false
          this.$message({
            message: this.$t('loc.shareSuccess'),
            type: 'success'
          })
          this.needReLoad = true
          this.handleClose()
        }).catch(error => {
          this.submitLoading = false
          this.$message.error(error.response.data.description)
        })
      }

    },
    updateNoteHandler (note) {
      this.submitLoading = true
      NoteApi.updateNote(note).then(res => {
        this.$message({
          message: this.$t('loc.uptSfy'),
          type: 'success'
        })
        this.needReLoad = true
        this.handleClose()
      }).catch(error => {
        this.$message.error(error.response.data.description)
      }).finally(() => {
        this.submitLoading = false
      })
    },
    selectedMeasureIdsHandler (measuresIds) {
      console.log(measuresIds)
      this.selectMeasureIds = measuresIds
    }
  }
}
</script>

<style scoped lang="less">
/deep/ .el-dialog__header {
  border-bottom: 0 !important;
  padding-bottom: 0;

  .el-dialog__title {
    font-size: 24px;
    color: #58666e;
  }
}

/deep/ .el-dialog__footer {
  border-top: 1px solid #e5e5e5;
  padding: 20px;
}

/deep/ .el-dialog {
  box-shadow: 0 5px 15px rgba(0, 0, 0, .5);
  border: 1px solid rgba(0, 0, 0, .2);
  border-radius: 6px;
  padding: 0;
}
.el-form-item__label {
  padding: 0 20px 0 0;
}
.child-list {
  display: flex;
  flex-wrap: wrap;

  .child-item {
    margin: 10px;
  }

  .child-name {
    max-width: 120px;
    text-overflow: ellipsis;
    overflow: hidden;
    white-space: nowrap;
    text-align: center;
  }
}

.select-measures-btn {
  color: #d4d4d4;
  background-color: #fff;
  border: 2px dashed #d4d4d4;
}
</style>